'use client';

import { useState, useEffect } from 'react';
import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query';
import { useTranslation } from 'react-i18next';
import { Button } from '@/components/ui/button';
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card';
import { PublicLayout } from '@/components/layout/public-layout';
import { formatAddress, formatDate, formatCurrency, formatTokenAmount } from '@/lib/utils';
import { multiChainApi } from '@/lib/multi-chain-api';
import { useChain } from '@/context/ChainContext';
import { API_ENDPOINTS } from '@/config/api';
import { useNetworkInfo, getExplorerUrl } from '@/hooks/useNetworkInfo';
import { useWeb3 } from '@/hooks/useWeb3';
import { useVestingContract } from '@/hooks/useVestingContract';
import { useVestingData } from '@/hooks/useVestingData';
import { 
  Clock, TrendingUp, Calendar, Lock, 
  CheckCircle, AlertCircle, ArrowRight,
  Download, Timer, Wallet, Info,
  ExternalLink, RefreshCw, Zap
} from 'lucide-react';
import toast from 'react-hot-toast';

interface VestingSchedule {
  schedule_id: string;
  beneficiary: string;
  total_amount: string;
  start_time: number;
  released_amount: string;
  releasable_amount: string;
  revoked: boolean;
  category: string;
  total_amount_formatted: string;
  released_amount_formatted: string;
  releasable_amount_formatted: string;
  start_time_iso: string;
}

interface VestingSummary {
  total_vested: string;
  total_released: string;
  total_releasable: string;
  schedule_count: number;
  total_vested_formatted: string;
  total_released_formatted: string;
  total_releasable_formatted: string;
}

interface VestingData {
  wallet_address: string;
  summary: VestingSummary;
  schedules: VestingSchedule[];
}

const getCategoryLabels = (t: any) => ({
  founding: t('allocations.categories.founding'),
  technical: t('allocations.categories.technical'),
  operations: t('allocations.categories.operations'),
  institutional: t('allocations.categories.institutional')
});

// Helper functions for safe number parsing
const parseFormattedNumber = (value: string): number => {
  return parseFloat(value.replace(/,/g, '') || '0');
};

const calculatePercentage = (numerator: string, denominator: string): number => {
  const num = parseFormattedNumber(numerator);
  const denom = parseFormattedNumber(denominator);
  return denom > 0 ? (num / denom) * 100 : 0;
};

export default function MyVestingPage() {
  const { t } = useTranslation('vesting');
  const categoryLabels = getCategoryLabels(t);
  const queryClient = useQueryClient();
  const { currentChain } = useChain();
  const [showClaimModal, setShowClaimModal] = useState(false);
  const [selectedSchedule, setSelectedSchedule] = useState<VestingSchedule | null>(null);
  const [vestingContractAddress, setVestingContractAddress] = useState<string>('');
  
  // Web3 hooks
  const { provider, account, isConnected, connect, isConnecting } = useWeb3();
  const vestingContract = useVestingContract(vestingContractAddress);
  
  // Get network info for explorer URLs
  const { data: networkInfo } = useNetworkInfo();

  // Invalidate queries when chain changes
  useEffect(() => {
    queryClient.invalidateQueries();
    setVestingContractAddress(''); // Reset contract address
  }, [currentChain, queryClient]);

  // Fetch contract addresses first
  const { data: contractAddresses } = useQuery({
    queryKey: ['contractAddresses', currentChain],
    queryFn: async () => {
      const response = await multiChainApi.getClient(currentChain).get(API_ENDPOINTS.contracts.info);
      return response.data.addresses;
    },
  });

  // Set vesting contract address when available
  useEffect(() => {
    if (contractAddresses?.dtv_vesting) {
      setVestingContractAddress(contractAddresses.dtv_vesting);
    }
  }, [contractAddresses]);

  // 使用前端直接查詢區塊鏈數據（避免後端轉發）
  const { 
    data: vestingData, 
    isLoading: isLoadingDirect, 
    error: directError, 
    refetch 
  } = useVestingData(vestingContractAddress, account || undefined); // Pass account directly

  // 如果前端直接查詢失敗，才使用後端 API 作為備份
  // Use connected wallet address (no admin login required)
  const queryWalletAddress = account;
  const { 
    data: vestingDataFromAPI, 
    isLoading: isLoadingAPI 
  } = useQuery<VestingData | null>({
    queryKey: ['upgradeableVesting', currentChain, queryWalletAddress],
    queryFn: async () => {
      if (!queryWalletAddress) return null;
      const response = await multiChainApi.getClient(currentChain).get(
        API_ENDPOINTS.contracts.vesting.beneficiary(queryWalletAddress)
      );
      return response.data;
    },
    enabled: !!queryWalletAddress && !!directError, // 只在直接查詢失敗時啟用
  });

  // 優先使用直接查詢的數據，如果失敗則使用 API 數據
  const finalVestingData = vestingData || vestingDataFromAPI;
  const isLoading = isLoadingDirect || (directError && isLoadingAPI);
  const error = directError && !vestingDataFromAPI ? directError : null;

  // Debug connection state
  useEffect(() => {
    console.log('My Vesting Page - Connection State:', {
      isConnected,
      account,
      provider: !!provider,
      vestingContractAddress,
      vestingData: !!vestingData,
      vestingDataFromAPI: !!vestingDataFromAPI,
      finalVestingData: !!finalVestingData,
      isLoading,
      error: error?.message
    });
  }, [isConnected, account, provider, vestingContractAddress, vestingData, vestingDataFromAPI, finalVestingData, isLoading, error]);

  // Web3 Release tokens mutation
  const web3ReleaseMutation = useMutation({
    mutationFn: async ({ scheduleId }: { scheduleId?: string }) => {
      if (!isConnected) {
        throw new Error('Please connect your wallet first');
      }
      
      if (!account) {
        throw new Error('No wallet connected');
      }
      
      // Allow beneficiaries to claim their own tokens
      // The vesting contract itself handles access control
      return await vestingContract.releaseTokens(scheduleId);
    },
    onSuccess: (result, variables) => {
      if (result.success) {
        // Refresh vesting data after successful transaction
        setTimeout(() => {
          queryClient.invalidateQueries({ queryKey: ['upgradeableVesting', currentChain, queryWalletAddress] });
          refetch();
        }, 2000); // Wait 2 seconds for blockchain to update
        
        setShowClaimModal(false);
        setSelectedSchedule(null);
      }
    },
    onError: (error: any) => {
      console.error('Web3 release error:', error);
    }
  });

  const getTotalProgress = () => {
    if (!finalVestingData?.summary) return 0;
    return calculatePercentage(
      finalVestingData.summary.total_released_formatted,
      finalVestingData.summary.total_vested_formatted
    );
  };

  const handleConnectWallet = async () => {
    const connected = await connect();
    if (connected) {
      toast.success(t('common.success'));
    }
  };

  const handleReleaseAll = () => {
    web3ReleaseMutation.mutate({});
  };

  const handleReleaseSpecific = (schedule: VestingSchedule) => {
    web3ReleaseMutation.mutate({ scheduleId: schedule.schedule_id });
  };

  // This function is no longer needed - any wallet can view their vesting data
  // Admin wallet validation is only done for claiming tokens

  // Check if wallet can claim tokens
  const canClaimTokens = () => {
    // Any connected wallet can attempt to claim
    // The smart contract will enforce who can actually claim
    return isConnected && account;
  };

  if (isLoading) {
    return (
      <PublicLayout>
        <div className="flex flex-col items-center justify-center h-64 space-y-4">
          <div className="animate-spin rounded-full h-12 w-12 border-b-2 border-blue-600"></div>
          <p className="text-gray-500">{t('allocations.loading')}</p>
          <p className="text-sm text-gray-400">{t('myVesting.loadingNote')}</p>
        </div>
      </PublicLayout>
    );
  }

  return (
    <PublicLayout>
      <div className="space-y-6">
          {/* Header */}
          <div className="flex items-center justify-between">
            <div>
              <h1 className="text-3xl font-bold">{t('myVesting.title')}</h1>
              <p className="text-muted-foreground">
                {t('myVesting.subtitle')}
              </p>
            </div>
            <div className="flex gap-2">
              {isConnecting ? (
                <div className="flex items-center gap-2 px-3 py-2 bg-blue-100 text-blue-800 rounded-md text-sm">
                  <RefreshCw className="h-4 w-4 animate-spin" />
                  <span>{t('common.wallet.connecting')}</span>
                </div>
              ) : !isConnected ? (
                <Button
                  onClick={handleConnectWallet}
                  className="flex items-center gap-2"
                  disabled={isConnecting}
                >
                  <Wallet className="h-4 w-4" />
                  {t('common.wallet.connect')}
                </Button>
              ) : (
                <div className="flex items-center gap-2 px-3 py-2 bg-green-100 text-green-800 rounded-md text-sm">
                  <CheckCircle className="h-4 w-4" />
                  <span>{t('common.wallet.connected')}: {formatAddress(account || '')}</span>
                </div>
              )}
              <Button
                variant="outline"
                onClick={() => {
                  queryClient.invalidateQueries({ queryKey: ['upgradeableVesting', currentChain] });
                  refetch();
                }}
                className="flex items-center gap-2"
              >
                <RefreshCw className="h-4 w-4" />
                {t('common.refresh')}
              </Button>
            </div>
          </div>

          {error && (
            <Card className="border-red-200 bg-red-50">
              <CardContent className="p-4">
                <div className="flex items-center gap-2 text-red-800">
                  <AlertCircle className="h-4 w-4" />
                  <span>{t('myVesting.loadError')}: {error.message}</span>
                </div>
              </CardContent>
            </Card>
          )}

          {!account ? (
            <Card>
              <CardContent className="p-12 text-center">
                <Wallet className="mx-auto h-12 w-12 text-gray-400 mb-4" />
                <h3 className="text-lg font-medium text-gray-900 mb-2">{t('myVesting.connectWallet.title')}</h3>
                <p className="text-gray-600 mb-4">
                  {t('myVesting.connectWallet.description')}
                </p>
                <Button onClick={handleConnectWallet} disabled={isConnecting}>
                  {isConnecting ? (
                    <>
                      <RefreshCw className="h-4 w-4 mr-2 animate-spin" />
                      {t('common.wallet.connecting')}
                    </>
                  ) : (
                    <>
                      <Wallet className="h-4 w-4 mr-2" />
                      {t('common.wallet.connect')}
                    </>
                  )}
                </Button>
              </CardContent>
            </Card>
          ) : !finalVestingData?.summary || finalVestingData.summary.schedule_count === 0 ? (
            <Card>
              <CardContent className="p-12 text-center">
                <Wallet className="mx-auto h-12 w-12 text-gray-400 mb-4" />
                <h3 className="text-lg font-medium text-gray-900 mb-2">{t('myVesting.noAllocation')}</h3>
                <p className="text-gray-600">
                  {t('myVesting.noAllocationDesc')}
                </p>
                <p className="text-sm text-gray-500 mt-2">
                  {t('myVesting.walletAddress')}: {queryWalletAddress || t('myVesting.noWalletConnected')}
                </p>
              </CardContent>
            </Card>
          ) : (
            <>
              {/* Overview Cards */}
              <div className="grid gap-4 md:grid-cols-2 lg:grid-cols-4">
                <Card>
                  <CardHeader className="flex flex-row items-center justify-between space-y-0 pb-2">
                    <CardTitle className="text-sm font-medium">{t('myVesting.stats.totalVested')}</CardTitle>
                    <Wallet className="h-4 w-4 text-muted-foreground" />
                  </CardHeader>
                  <CardContent>
                    <div className="text-2xl font-bold">
                      {finalVestingData.summary.total_vested_formatted} DTV
                    </div>
                    <p className="text-xs text-muted-foreground">
                      {finalVestingData.summary.schedule_count} {t('myVesting.stats.schedules')}
                    </p>
                  </CardContent>
                </Card>

                <Card>
                  <CardHeader className="flex flex-row items-center justify-between space-y-0 pb-2">
                    <CardTitle className="text-sm font-medium">{t('myVesting.stats.totalReleased')}</CardTitle>
                    <CheckCircle className="h-4 w-4 text-green-600" />
                  </CardHeader>
                  <CardContent>
                    <div className="text-2xl font-bold">
                      {finalVestingData.summary.total_released_formatted} DTV
                    </div>
                    <p className="text-xs text-muted-foreground">
                      {getTotalProgress().toFixed(1)}% {t('myVesting.stats.claimed')}
                    </p>
                  </CardContent>
                </Card>

                <Card>
                  <CardHeader className="flex flex-row items-center justify-between space-y-0 pb-2">
                    <CardTitle className="text-sm font-medium">{t('myVesting.stats.available')}</CardTitle>
                    <Download className="h-4 w-4 text-blue-600" />
                  </CardHeader>
                  <CardContent>
                    <div className="text-2xl font-bold text-blue-600">
                      {finalVestingData.summary.total_releasable_formatted} DTV
                    </div>
                    <p className="text-xs text-muted-foreground">
                      {t('myVesting.stats.readyToClaim')}
                    </p>
                  </CardContent>
                </Card>

                <Card>
                  <CardHeader className="flex flex-row items-center justify-between space-y-0 pb-2">
                    <CardTitle className="text-sm font-medium">{t('myVesting.stats.remaining')}</CardTitle>
                    <Lock className="h-4 w-4 text-orange-600" />
                  </CardHeader>
                  <CardContent>
                    <div className="text-2xl font-bold">
                      {formatTokenAmount(
                        parseFormattedNumber(finalVestingData.summary.total_vested_formatted) - 
                        parseFormattedNumber(finalVestingData.summary.total_released_formatted) -
                        parseFormattedNumber(finalVestingData.summary.total_releasable_formatted)
                      )} DTV
                    </div>
                    <p className="text-xs text-muted-foreground">
                      {t('myVesting.stats.stillVesting')}
                    </p>
                  </CardContent>
                </Card>
              </div>

              {/* Global Release Action */}
              {parseFloat(finalVestingData.summary.total_releasable_formatted) > 0 && (
                <Card className="border-blue-200 bg-blue-50">
                  <CardContent className="p-6">
                    <div className="flex items-center justify-between">
                      <div>
                        <h3 className="text-lg font-medium text-blue-900">
                          {t('myVesting.claimAll.title')}
                        </h3>
                        <p className="text-blue-700">
                          {t('myVesting.claimAll.description', { amount: finalVestingData.summary.total_releasable_formatted })}
                        </p>
                      </div>
                      <Button
                        onClick={handleReleaseAll}
                        disabled={web3ReleaseMutation.isPending || !canClaimTokens()}
                        className="bg-blue-600 hover:bg-blue-700 disabled:opacity-50"
                      >
                        {web3ReleaseMutation.isPending ? (
                          <>
                            <RefreshCw className="h-4 w-4 mr-2 animate-spin" />
                            {t('myVesting.claimAll.processing')}
                          </>
                        ) : !canClaimTokens() ? (
                          <>
                            <Wallet className="h-4 w-4 mr-2" />
                            {t('myVesting.claimAll.connectRequired')}
                          </>
                        ) : (
                          <>
                            <Zap className="h-4 w-4 mr-2" />
                            {t('myVesting.claimAll.button')}
                          </>
                        )}
                      </Button>
                    </div>
                  </CardContent>
                </Card>
              )}

              {/* Vesting Schedules */}
              <Card>
                <CardHeader>
                  <CardTitle>{t('myVesting.schedules.title')}</CardTitle>
                  <CardDescription>{t('myVesting.schedules.subtitle')}</CardDescription>
                </CardHeader>
                <CardContent>
                  <div className="space-y-4">
                    {finalVestingData.schedules.map((schedule, index) => (
                      <div key={schedule.schedule_id} className="border rounded-lg p-4">
                        <div className="flex items-center justify-between mb-4">
                          <div>
                            <h4 className="font-medium">
                              {categoryLabels[schedule.category as keyof typeof categoryLabels] || schedule.category}
                            </h4>
                            <p className="text-sm text-muted-foreground">
                              {t('myVesting.schedules.started')}: {formatDate(schedule.start_time_iso)}
                            </p>
                          </div>
                          {schedule.revoked && (
                            <span className="px-2 py-1 bg-red-100 text-red-800 rounded-full text-xs">
                              Revoked
                            </span>
                          )}
                        </div>

                        <div className="grid grid-cols-2 md:grid-cols-4 gap-4 mb-4">
                          <div>
                            <p className="text-sm text-muted-foreground">Total Amount</p>
                            <p className="font-medium">{schedule.total_amount_formatted} DTV</p>
                          </div>
                          <div>
                            <p className="text-sm text-muted-foreground">Released</p>
                            <p className="font-medium">{schedule.released_amount_formatted} DTV</p>
                          </div>
                          <div>
                            <p className="text-sm text-muted-foreground">Available</p>
                            <p className="font-medium text-blue-600">{schedule.releasable_amount_formatted} DTV</p>
                          </div>
                          <div className="flex justify-end">
                            {parseFloat(schedule.releasable_amount_formatted) > 0 && !schedule.revoked && (
                              <Button
                                size="sm"
                                onClick={() => handleReleaseSpecific(schedule)}
                                disabled={web3ReleaseMutation.isPending || !canClaimTokens()}
                                className="disabled:opacity-50"
                                title={!canClaimTokens() ? "Connect wallet to claim tokens" : "Claim available tokens"}
                              >
                                {web3ReleaseMutation.isPending ? (
                                  <RefreshCw className="h-4 w-4 animate-spin" />
                                ) : !canClaimTokens() ? (
                                  <Wallet className="h-4 w-4" />
                                ) : (
                                  <>
                                    <Zap className="h-4 w-4 mr-1" />
                                    Claim
                                  </>
                                )}
                              </Button>
                            )}
                          </div>
                        </div>

                        {/* Progress Bar */}
                        <div className="space-y-2">
                          <div className="flex justify-between text-sm">
                            <span>{t('myVesting.schedules.progress')}</span>
                            <span>
                              {calculatePercentage(
                                schedule.released_amount_formatted,
                                schedule.total_amount_formatted
                              ).toFixed(1)}%
                            </span>
                          </div>
                          <div className="w-full bg-gray-200 rounded-full h-2">
                            <div
                              className="bg-blue-600 h-2 rounded-full"
                              style={{
                                width: `${calculatePercentage(
                                  schedule.released_amount_formatted,
                                  schedule.total_amount_formatted
                                )}%`
                              }}
                            />
                          </div>
                        </div>
                      </div>
                    ))}
                  </div>
                </CardContent>
              </Card>

              {/* Contract Information */}
              <Card>
                <CardHeader>
                  <CardTitle>Contract Information</CardTitle>
                  <CardDescription>Details about the vesting contract</CardDescription>
                </CardHeader>
                <CardContent>
                  <div className="space-y-2">
                    <div className="flex justify-between">
                      <span className="text-sm text-muted-foreground">Contract Type</span>
                      <span className="text-sm font-medium">UUPS Upgradeable</span>
                    </div>
                    <div className="flex justify-between">
                      <span className="text-sm text-muted-foreground">Vesting Duration</span>
                      <span className="text-sm font-medium">84 months (7 years)</span>
                    </div>
                    <div className="flex justify-between">
                      <span className="text-sm text-muted-foreground">Cliff Period</span>
                      <span className="text-sm font-medium">None (immediate vesting)</span>
                    </div>
                    <div className="flex justify-between">
                      <span className="text-sm text-muted-foreground">Release Type</span>
                      <span className="text-sm font-medium">Linear</span>
                    </div>
                    {networkInfo && (
                      <div className="flex justify-between">
                        <span className="text-sm text-muted-foreground">View Contract</span>
                        <Button
                          variant="ghost"
                          size="sm"
                          className="p-0 h-auto"
                          onClick={() => window.open(
                            `${networkInfo.explorerUrl}/address/${vestingContractAddress}`,
                            '_blank'
                          )}
                        >
                          <ExternalLink className="h-3 w-3 mr-1" />
                          Explorer
                        </Button>
                      </div>
                    )}
                  </div>
                </CardContent>
              </Card>
            </>
          )}
        </div>
    </PublicLayout>
  );
}